package com.huang;

import com.huang.server.RemoteProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
@EnableFeignClients
@SpringBootApplication
public class SumApp {
    public static void main(String[] args) {
        SpringApplication.run(SumApp.class, args);
    }

    @Bean
    public RestTemplate restTemplate(){

        return new RestTemplate();
    }

    @Bean
    @LoadBalanced
   public RestTemplate   loadBalancedRestTemplate(){
       return new RestTemplate();


   }


  @RestController
  public class consumer{
    //没有负载的一种，因为凭借了请求路径的固定端口号
      @Resource
      public RestTemplate restTemplate;
      //第一种负载。凭借了数据的端口号
      @Resource
      private LoadBalancerClient loadBalancerClient;
     //第二种负载。不用拼接端口号，直接访问服务的端口号，方便访问问
      @Autowired
     public  RestTemplate loadBalancedRestTemplate;

      //注入openfegin的接口
      @Autowired
     private RemoteProviderService remoteProviderService;



      @GetMapping("/doecho")
      public  String doecho(){
          String url="http://localhost:8093/echo/"+"sdef";
          return  restTemplate.getForObject(url, String.class);
        }

      //实现负载均衡1
      @GetMapping("/doecho1")
       public String doecho1(){
          ServiceInstance instance=loadBalancerClient.choose("provider");
          String url =String.format("http://%s:%s/echo/%s", instance.getHost(),instance.getPort(),"sssssdfasfas");
         return restTemplate.getForObject(url, String.class);
       }
      //实现负载均衡2
      @GetMapping("/doecho2")
      public String doecho2(){
          String url =String.format("http://%s/echo/%s", "provider","sssss");
          return loadBalancedRestTemplate.getForObject(url, String.class);
      }
      @GetMapping("/doecho3/{msg}")
      public  String doecho3( @PathVariable String msg){
          return remoteProviderService.echoMessage(msg);
      }

}
}
